<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('修改医院')" />
    <th:block th:include="include :: datetimepicker-css"/>
    <th:block th:include="include :: bootstrap-fileinput-css"/>
    <th:block th:include="include :: summernote-css"/>
    <th:block th:include="include :: jquery-smartwizard-css"/>
    <th:block th:include="include :: select2-css"/>
    <th:block th:include="include :: bootstrap-select-css"/>
    <th:block th:include="include :: summernote-css"/>
</head>
<script src="../static/js/xm-select.js" th:src="@{/js/xm-select.js}"></script>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-hospital-edit" th:object="${hospital}" style="padding: 20px">
            <input name="id" th:field="*{id}" type="hidden">
            <div class="form-group">
                <div class="col-sm-6">
                    <label class="col-sm-2 control-label">医院名称：</label>
                    <div class="col-sm-10">
                        <input name="hospitalName" th:field="*{hospitalName}" class="form-control" type="text">
                    </div>
                </div>
                <div class="col-sm-6">
                    <label class="col-sm-2 control-label">医院英文名称：</label>
                    <div class="col-sm-10">
                        <input name="hospitalEnglishName" th:field="*{hospitalEnglishName}" class="form-control" type="text">
                    </div>
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-6">
                    <label class="col-sm-2 control-label">标题：</label>
                    <div class="col-sm-10">
                        <input name="title" th:field="*{title}" class="form-control" type="text">
                    </div>
                </div>
                <div class="col-sm-6">
                    <label class="col-sm-2 control-label">描述：</label>
                    <div class="col-sm-10">
                        <input name="description" th:field="*{description}" class="form-control" type="text">
                    </div>
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-6">
                    <label class="col-sm-2 control-label">关键词：</label>
                    <div class="col-sm-10">
                        <input name="keywords" th:field="*{keywords}" class="form-control" type="text">
                    </div>
                </div>
                <div class="col-sm-6">
                    <label class="col-sm-2 control-label">选择疾病：</label>
                    <div class="col-sm-10">
                        <div id="selectDemo"></div>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-1 control-label">主图：</label>
                <div class="col-sm-11">
                    <input type="hidden" th:value="*{hospitalImgPath}" name="hospitalImgPath">
                    <div class="file-loading">
                        <input class="form-control file-upload"  id="hospitalImgPath" name="file" type="file">
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-1 control-label">医院简介：</label>
                <div class="col-sm-11">
                    <textarea name="content" class="form-control">[[*{content}]]</textarea>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-1 control-label">医院介绍：</label>
                <div class="col-sm-11">
                    <input type="hidden" class="form-control" th:field="*{introduce}">
                    <div class="summernote" id="introduce"></div>
                </div>
            </div>
        </form>
    </div>
    <th:block th:include="include :: footer"/>
    <th:block th:include="include :: datetimepicker-js"/>
    <th:block th:include="include :: bootstrap-fileinput-js"/>
    <th:block th:include="include :: summernote-js"/>
    <th:block th:include="include :: jquery-smartwizard-js"/>
    <th:block th:include="include :: select2-js"/>
    <th:block th:include="include :: bootstrap-select-js"/>
    <th:block th:include="include :: summernote-js"/>
    <script src="/ueditor/ueditor.config.js" type="text/javascript" charSet="utf-8"></script>
    <script src="/ueditor/ueditor.all.js" type="text/javascript" charSet="utf-8"></script>
    <script src="/ueditor/lang/zh-cn/zh-cn.js" type="text/javascript" charSet="utf-8"></script>
    <script th:inline="javascript">
        var prefix = ctx + "ydz/hospital";
        var diseasearr = [[${hospital}]].hospitalDiseases
        var disarr = [];
        var backdis = [];
        var selectData = [];
        $("#form-hospital-edit").validate({
            focusCleanup: true
        });

        function submitHandler() {
            if ($.validate.form()) {
                var jsons = {};
                let formData = $('#form-hospital-edit').serializeArray();
                $.each(formData, function (k, v) {
                    jsons[v.name] = v.value;
                });
                const factoryArray = disarr.map(item1 => {
                    // 查找factoryArr中enterpriseId相同的元素
                    const match = diseasearr.find(item2 => item2.diseaseId === item1.diseaseId);
                    if (match) {
                        // 如果有相同enterpriseId的对象，则合并两个对象
                        return { ...item1, ...match };
                    }
                    return item1;  // 没有匹配项则返回原来的对象
                }).concat(diseasearr.filter(item2 =>
                    !disarr.some(item1 => item1.diseaseId === item2.diseaseId)
                ));

                jsons["hospitalDiseases"] = factoryArray
                var value = JSON.stringify(jsons)
                save(prefix + "/edit", value);
            }
        }

        //初始化加载
        $(document).ready(function () {
            parent.$('body').find('.layui-layer-max:not(.layui-layer-maxmin)').click()

            //回显疾病多选
            if (null != diseasearr){
                diseasearr.forEach(item=>{
                    let obj = {}
                    obj.diseaseId = item.diseaseId
                    obj.hospitalId = item.hospitalId
                    obj.id = item.id
                    disarr.push(obj)
                    backdis.push(item.diseaseId.toString())
                })
            }
            //加载疾病下拉
            $.ajax({
                url: "/api/common/selectJapanDisease/01",
                type: "get",
                success: res => {
                    alldis = res.data
                    for (let i = 0; i < alldis.length; i++){
                        let val = {}
                        val.name = alldis[i].name
                        val.diseaseId = alldis[i].id
                        selectData.push(val)
                    }
                    initXmSelect()
                }
            })
        })

        $(".file-upload").each(function (i) {
            var val = $("input[name='" + this.id + "']").val()
            if (val==""){
                $(".file-upload").fileinput({
                    uploadUrl: ctx + 'common/upload',
                    maxFileCount: 1,
                    autoReplace: true
                }).on('fileuploaded', function (event, data, previewId, index) {
                    $("input[name='" + event.currentTarget.id + "']").val(data.response.fileName)
                }).on('fileremoved', function (event, id, index) {
                    $("input[name='" + event.currentTarget.id + "']").val('')
                })
            }else{
                $(this).fileinput({
                    'uploadUrl': ctx + 'common/upload',
                    initialPreviewAsData: true,
                    initialPreview: [val],
                    maxFileCount: 1,
                    autoReplace: true
                }).on('fileuploaded', function (event, data, previewId, index) {
                    $("input[name='" + event.currentTarget.id + "']").val(data.response.fileName)
                }).on('fileremoved', function (event, id, index) {
                    $("input[name='" + event.currentTarget.id + "']").val('')
                })
                $(this).fileinput('_initFileActions');
            }
        });

        //json请求
        function save(url, data, callback) {
            var config = {
                url: url,
                type: "post",
                dataType: "json",
                data: data,
                headers: {
                    'Content-Type': 'application/json;charset=utf8'
                },
                beforeSend: function () {
                    $.modal.loading("正在处理中，请稍候...");
                    $.modal.disable();
                },
                success: function (result) {
                    if (typeof callback == "function") {
                        callback(result);
                    }
                    $.operate.successCallback(result);
                }
            };
            $.ajax(config)
        }

        //疾病多选
        function initXmSelect(){
            xmSelect.render({
                el: '#selectDemo',
                checkbox: true,
                repeat: false,
                autoRow: true,
                filterable: true,
                prop: {name: 'name', value: 'diseaseId',id:'id'},
                initValue: backdis,//回显
                height: '200px',
                tips: '请选择',
                tree: {
                    show: true,
                    showFolderIcon: true,
                    showLine: true,
                    indent: 20,
                    expandedKeys: [-3],
                    strict: false,
                },
                data: function () {
                    return selectData
                },
                on: function (data) {
                    disarr = data.arr;//arr:  当前多选已选中的数据
                    changeFactory(data.change,data.isAdd);
                },
            });
        }

        function changeFactory(obj,flag) {
            var factoryBean={}
            obj.forEach(item => {
                factoryBean = item;
            });
            //删除新标签时
            if(!flag && null != diseasearr){
                //查找回显集合中的元素，有则更改有效性，没有则忽略
                const factory = diseasearr.find(item => item.diseaseId === factoryBean.diseaseId);
                if (factory) {
                    factory.delFlag = "1";  // 修改有效性为1,（无效，用作删除）
                }
            }
        }

        $(function() {
            $('.summernote').each(function(i) {
                $('#' + this.id).summernote({
                    lang: 'zh-CN',
                    dialogsInBody: true,
                    callbacks: {
                        onChange: function(contents, $edittable) {
                            $("input[name='" + this.id + "']").val(contents);
                        },
                        onImageUpload: function(files) {
                            var obj = this;
                            var data = new FormData();
                            data.append("file", files[0]);
                            $.ajax({
                                type: "post",
                                url: ctx + "common/upload",
                                data: data,
                                cache: false,
                                contentType: false,
                                processData: false,
                                dataType: 'json',
                                success: function(result) {
                                    if (result.code == web_status.SUCCESS) {
                                        $('#' + obj.id).summernote('insertImage', result.url);
                                    } else {
                                        $.modal.alertError(result.msg);
                                    }
                                },
                                error: function(error) {
                                    $.modal.alertWarning("图片上传失败。");
                                }
                            });
                        }
                    }
                });
                var content = $("input[name='" + this.id + "']").val();
                $('#' + this.id).summernote('code', content);
            })
        });
    </script>
</body>
</html>